//
//  GZPullDownRefreshControl.swift
//  sinaweibo
//
//  Created by mac book pro on 16/3/30.
//  Copyright © 2016年 finish. All rights reserved.
//

import UIKit


/// 刷新控件状态
enum GRefreshControlStatus:Int {
    case Normal  //尖头向下
    case PullToRefresh //尖头向上
    case Refreshing //正在刷新
}
/// 高度
let GRefreshControlHeight: CGFloat = 60
class GZPullDownRefreshControl: UIView {
    //MARK: -属性
    var lastRefreshStatus: GRefreshControlStatus?
    /// 当前刷新状态
    var currentRefreshStatus: GRefreshControlStatus = .Normal{
        didSet{ //根据状态改变 设置相应内容
            switch currentRefreshStatus{
            case .Normal:
                arrowView.hidden = false
                rotationView.hidden = true
                messageLabel.text = "下拉刷新"
                //清空动画
                UIView.animateWithDuration(defalutanimationDuration, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })
                //刷新完毕后，需要隐藏控件
                if lastRefreshStatus == .Refreshing{
                    UIView.animateWithDuration(defalutanimationDuration, animations: { () -> Void in
                        self.scrollView.contentInset.top -= GRefreshControlHeight
                    })
                }
            case .PullToRefresh:
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(defalutanimationDuration, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI - 0.0001))
                })
            case .Refreshing:
                arrowView.hidden = true
                rotationView.hidden = false
                messageLabel.text = "正在拼命刷新..."
                //转动动画
                let rotation = CABasicAnimation(keyPath: "transform.rotation")
                rotation.toValue = M_PI * 2
                rotation.duration = 0.5
                rotation.repeatCount = MAXFLOAT
                rotationView.layer.addAnimation(rotation, forKey: "rotation")
                
                //需要显示刷新控件
                UIView.animateWithDuration(defalutanimationDuration, animations: { () -> Void in
                    self.scrollView.contentInset.top += GRefreshControlHeight
                })
                //调用必包
                pullToRefreshHandler?()
            }
            lastRefreshStatus = currentRefreshStatus
        }
    }
    func beginRefreshing(){
        currentRefreshStatus = .Refreshing
    }
    //结束刷新
    func endRefreshing(){
        currentRefreshStatus = .Normal
    }
    /// 下啦刷新闭包
    var pullToRefreshHandler:(()->())?
    /// 父控件
    var scrollView: UIScrollView! //！代表可选 没有值 会报错
    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: -GRefreshControlHeight, width: UIScreen.width, height: GRefreshControlHeight)
        super.init(frame: newFrame)
        self.backgroundColor = UIColor.brownColor()
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func prepareUI(){
        addSubview(arrowView)
        addSubview(rotationView)
        addSubview(messageLabel)
        
        rotationView.hidden = true
        //约束 原生的 不要依赖太多第三方
        arrowView.translatesAutoresizingMaskIntoConstraints = false
        rotationView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        //尖头
        addConstraint(NSLayoutConstraint(item: arrowView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -30))
        addConstraint(NSLayoutConstraint(item: arrowView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        // 小转轮
        addConstraint(NSLayoutConstraint(item: rotationView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: rotationView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        // 文字
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 10))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    }
    /**
    即将添加到父控件
    
    - parameter newSuperview: 父控件
    */
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let scorllView = newSuperview as? UIScrollView{
            self.scrollView = scorllView
            //添加监听KVO
            scorllView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        }
        
    }
    //监听回调
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //当手指在拖动
        if scrollView.dragging {
            if currentRefreshStatus == .PullToRefresh  &&  scrollView.contentOffset.y > -scrollView.contentInset.top-GRefreshControlHeight{
                currentRefreshStatus = .Normal
            }else if currentRefreshStatus == .Normal  && scrollView.contentOffset.y <=  -scrollView.contentInset.top-GRefreshControlHeight{
                currentRefreshStatus = .PullToRefresh
            }
            
        }else if currentRefreshStatus == .PullToRefresh {
            currentRefreshStatus = .Refreshing//刷新状态
        }
    }
    
    deinit{
        //移除监听
        superview?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //MARK: -lazy load
    private lazy var arrowView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var rotationView: UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.darkGrayColor()
        label.font = UIFont.systemFontOfSize(14)
        label.text = "下啦刷新"
        label.sizeToFit() //自适应大小
        return label
        
        }()
}
